from flask import Flask, jsonify, request, render_template,url_for,redirect,session,send_from_directory
from uuid import uuid4
import requests
import json
import modules.net.pynet
import os
import util.chash
import modules.db
import tempfile
import webapp.webapputil
class WebApp:
    def __init__(self):
        self.__attachApi()
    def __call__(self):
        return self
    @staticmethod
    def ifTelIsRegistered(tel):
        result=modules.db.Sqlite3Db.user_findByTel(tel)
        if result!=None and len(result)>0:
            return True
        else:
            return False
    @staticmethod
    def ifTelAndPwdIsRight(tel,pwd):
        result=modules.db.Sqlite3Db.user_findByTelAndPwd(tel,pwd)
        if result!=None and len(result)>0:
            return True
        else:
            return False
    

    
    @staticmethod
    def registerPersonInfo(tel,username,pwd):
        return modules.db.Sqlite3Db.user_add(tel,username,pwd)

    def __attachApi(self):
       
        
        @modules.net.pynet.CP2pnet.severapp.route('/login',methods=['GET','POST'])
        def login():
            if request.method =='GET':
                return render_template('login.html')
            else:
                telephone =request.form.get("telephone")
                password = request.form.get("password")
                if WebApp.ifTelAndPwdIsRight(telephone,password):
                    session['user_id'] = telephone
                    response = {
                        'status':501,
                        'message':"登录成功"
                        }
                    return jsonify(response), 200
                else:
                    response = {
                        'status':50,
                        'message':"密码不正确"
                        }
                    return jsonify(response), 200
                
                

    
        @modules.net.pynet.CP2pnet.severapp.route('/register',methods=['GET','POST'])
        def register():
            if request.method =='GET':
                return render_template('register.html')
            else:
                telephone = request.form.get("telephone")
                username =request.form.get("username")
                password1 = request.form.get("password1")
                password2 = request.form.get("password2")
                result = WebApp.registerPersonInfo(telephone,username,password1)
                                                                                                                                                                                                      
                response = {
                        'status':501,
                        'message':"注册成功"
                        }
                return jsonify(response), 200
        @modules.net.pynet.CP2pnet.severapp.route('/register/person',methods=['POST'])
        def personregister():

            keyInfo=util.ccrypto.CCrypto.produceKey()
            response = {
                        'status':501,
                        'message':"注册成功",
                        'keyInfo':keyInfo
                        }
            return jsonify(response), 200
           
            # values = request.get_json()
            # required=['ID','username','password1','password2']
            # if values==None or not all(k in values for k in required):
            #     response = {
            #         'status':502,
            #         'message':"注册失败"
            #         }
            #     return jsonify(response), 200

            # ID =values["ID"]
            # username =values["username"]
            # password1 =values["password1"]
            # password2 =values["password2"]
            # result = WebApp.registerPersonInfo(ID,username,password1)
            # if result:
            #     keyInfo=webapp.webapputil.CwebAppUtil.produceNewCard(ID)
                                                                                                                                                                                                        
            #     response = {
            #             'status':501,
            #             'message':"注册成功",
            #             'keyInfo':keyInfo
            #             }
            #     return jsonify(response), 200
            # else:
            #     response = {
            #         'status':502,
            #         'message':"注册失败"
            #         }
            #     return jsonify(response), 200
        
        @modules.net.pynet.CP2pnet.severapp.route('/register/company',methods=['POST'])
        def companyregister():
            keyInfo=util.ccrypto.CCrypto.produceKey()
            response = {
                        'status':501,
                        'message':"注册成功",
                        'keyInfo':keyInfo
                        }
            return jsonify(response), 200
           
           
            # values = request.get_json()
            # required=['licenseCode','companyname','password1','password2']
            # if values==None or not all(k in values for k in required):
            #     response = {
            #         'status':502,
            #         'message':"注册失败"
            #         }
            #     return jsonify(response), 200

            # ID =values["licenseCode"]
            # username =values["companyname"]
            # password1 =values["password1"]
            # password2 =values["password2"]
            # result = WebApp.registerPersonInfo(ID,username,password1)
            # if result:
            #     keyInfo=webapp.webapputil.CwebAppUtil.produceNewCard(ID)
                                                                                                                                                                                                        
            #     response = {
            #             'status':501,
            #             'message':"注册成功",
            #             'keyInfo':keyInfo
            #             }
            #     return jsonify(response), 200
            # else:
            #     response = {
            #         'status':502,
            #         'message':"注册失败"
            #         }
            #     return jsonify(response), 200


        @modules.net.pynet.CP2pnet.severapp.route('/register/checkTel',methods=['GET','POST'])
        def checkRegisterTel():
            telephone = request.args.get("tel")
            if WebApp.ifTelIsRegistered(telephone):
                response = {
                        'status':500
                        }
                return jsonify(response), 200
               
            else:
                response = {
                         'status':501
                        }
                return jsonify(response), 200
        @modules.net.pynet.CP2pnet.severapp.route('/register/success',methods=['GET','POST'])
        def registersuccess():
            return render_template('registersuccess.html')

        @modules.net.pynet.CP2pnet.severapp.route('/register/newcard',methods=['GET','POST'])
        @modules.net.pynet.CP2pnet.login_required
        def registerNewCard():
            if request.method =='GET':
                return render_template('registernewcard.html')
            else:
                user_id=session.get('user_id')
                webapp.webapputil.CwebAppUtil.produceNewCard(user_id)
                response = {
                        'status':500
                        }
                return jsonify(response), 200

                  

        @modules.net.pynet.CP2pnet.severapp.route('/loginout')
        def loginout():
            session.clear()
            return redirect(url_for('login'))

        @modules.net.pynet.CP2pnet.severapp.route('/personInfo')
        @modules.net.pynet.CP2pnet.login_required
        def personInfo():
            #return render_template("index.html")
            return render_template("personInfo.html")
        
        @modules.net.pynet.CP2pnet.severapp.route('/personInfo/uploadsecret',methods=['GET','POST'])
        # @modules.net.pynet.CP2pnet.login_required
        def personInfouploadsecret():
            if request.method == "GET":
                return render_template("uploadsecret.html")

            else:
                user_id=session.get('user_id')
                #="18861846217"
                values = request.get_json()
                data = values['mydata']
                data =data.strip()
                data= data.replace("\r\n","\n")
                if util.ccrypto.CCrypto.ifIsRightPrivateKeyString(data):
                    flag= webapp.webapputil.CwebAppUtil.addCard(user_id,data)
                    if flag:
                        response = {
                            'status':500
                            }
                        return jsonify(response), 200
                    else:
                        response = {
                            'status':501
                            }
                        return jsonify(response), 200

                else:
                    response = {
                            'status':502
                            }
                    return jsonify(response), 200
                
               

        
        @modules.net.pynet.CP2pnet.severapp.route('/personInfo/uploadsecret/checksecret',methods=['POST'])
        def checkuploadsecret():
            values = request.get_json()
            required = ['mydata']
            if not all(k in values for k in required):
                response = {
                            'status':503
                            }
                return jsonify(response), 200
            
            data = values['mydata']
            data =data.strip()
            data= data.replace("\r\n","\n")
            if util.ccrypto.CCrypto.ifIsRightPrivateKeyString(data):
                response = {
                            'status':500
                            }
                return jsonify(response), 200
                
            else:
                response = {
                            'status':501
                            }
                return jsonify(response), 200
            
               
        
        
        @modules.net.pynet.CP2pnet.severapp.route('/personInfo/loadsecret/<address>')
        @modules.net.pynet.CP2pnet.login_required
        def downloadKey(address):
            user_id=session.get('user_id')
            result=modules.db.Sqlite3Db.card_findByAddressAndTel(address,user_id)
            privatekey=str(result[0][2])
            tempfile.tempdir=os.path.join(os.getcwd(),"temp")

            ntf=tempfile.NamedTemporaryFile()
            
            ntf.write(privatekey.encode('utf-8'))
            filepath=tempfile.gettempdir()
            filename=ntf.name.split('/')[-1]
            ntf.seek(0)
            result=send_from_directory(filepath, filename,as_attachment=True)
            ntf.close()
            return result
         
            
        @modules.net.pynet.CP2pnet.severapp.route('/transferAccounts/<sendaccount>')
        def transferAccounts(sendaccount):

            return render_template("transfer1.html",sendaccount=sendaccount)

        @modules.net.pynet.CP2pnet.severapp.route('/personInfo/accountlist',methods=['GET'])
        @modules.net.pynet.CP2pnet.login_required
        def accountlist():
            user_id=session.get('user_id')
            cardDirlist=webapp.webapputil.CwebAppUtil.getcardlists(user_id)
            if len(cardDirlist):
                return render_template("accountlist.html",cardDirlist=cardDirlist)
            else:
                return render_template("accountlist.html")
                
        @modules.net.pynet.CP2pnet.severapp.route('/transfer/success/<txhash>/<sender>/<recipient>/<amount>',methods=['GET'])
        def handleTransferSuccess(txhash,sender,recipient,amount):
           values={
               'txhash':txhash,
               'sender':sender,
               'recipient':recipient,
               'amount':amount
           }
           return render_template('transfer1success.html',values=values,txhash=txhash)
        
        @modules.net.pynet.CP2pnet.severapp.route('/getUnspentTx/<address>',methods=['GET'])
        # @modules.net.pynet.CP2pnet.login_required
        def getUTXOsByaddress(address):
            UTXOs=[]
            UTXOs= modules.transaction.CTransaction.findUnspentTransactions(address)

            return jsonify(UTXOs), 200
        
            
        @modules.net.pynet.CP2pnet.severapp.route('/hell0',methods=['POST'])
        def test():
            values = request.get_json()
            print(values)
            tx=values
            print(tx['selfhash'])
            print(util.chash.CHash.getTransactionHash(tx))
            response = {
                        'chain':"avc",
                        'length': 12,
                    }
            return jsonify(response), 200  

    

        @modules.net.pynet.CP2pnet.severapp.context_processor
        def my_context_processor():
             user_id=session.get('user_id')
             if user_id:
                 #从数据库中查询到用户的信息
                 return {'user':user_id}
             else:
                 return {}





